# filepath: d:\CompanyProject\Gitee\DBCompareX\backend\app\schemas\task_data_sync\execution.py
from pydantic import BaseModel, Field
from typing import Optional, Any, Dict, List
from datetime import datetime
from bson import ObjectId

class PyObjectId(ObjectId):
    @classmethod
    def __get_validators__(cls):
        yield cls.validate

    @classmethod
    def validate(cls, v):
        if not ObjectId.is_valid(v):
            raise ValueError("无效的ObjectId")
        return ObjectId(v)

    @classmethod
    def __modify_schema__(cls, field_schema):
        field_schema.update(type="string")

# 任务执行日志基础模型
class TaskDataSyncExecutionLogBase(BaseModel):
    task_data_sync_setting_id: str = Field(..., description="数据同步任务配置ID")
    batch_no: str = Field(..., description="执行批次号 (TDYYYYMMDD_序号)")
    status: int = Field(..., description="状态 (-1 失败，1 执行中，2 数据对比正常，3 数据对比失败)")
    message: Optional[str] = Field(None, description="信息 (可以记录异常信息)")

# 存储在数据库中的任务执行日志模型
class TaskDataSyncExecutionLogInDB(TaskDataSyncExecutionLogBase):
    id: PyObjectId = Field(default_factory=PyObjectId, alias="_id")
    created_at: datetime = Field(default_factory=datetime.now)

    class Config:
        allow_population_by_field_name = True
        arbitrary_types_allowed = True
        json_encoders = {
            ObjectId: str,
            datetime: lambda dt: dt.isoformat()
        }

# 目标数据和源数据基础模型
class TaskDataListBase(BaseModel):
    task_data_sync_execution_log_id: str = Field(..., description="数据同步任务执行日志ID")
    data: Dict[str, Any] = Field(..., description="动态数据字段")

# 存储在数据库中的目标数据模型
class TaskTargetListInDB(TaskDataListBase):
    id: PyObjectId = Field(default_factory=PyObjectId, alias="_id")

    class Config:
        allow_population_by_field_name = True
        arbitrary_types_allowed = True
        json_encoders = {
            ObjectId: str
        }

# 存储在数据库中的源数据模型
class TaskSourceListInDB(TaskDataListBase):
    id: PyObjectId = Field(default_factory=PyObjectId, alias="_id")
    task_target_list_id: str = Field(..., description="关联的目标数据ID")

    class Config:
        allow_population_by_field_name = True
        arbitrary_types_allowed = True
        json_encoders = {
            ObjectId: str
        }

# 目源对比结果基础模型
class TaskTsContrastResultBase(BaseModel):
    task_data_sync_execution_log_id: str = Field(..., description="数据同步任务执行日志ID")
    task_target_list_id: str = Field(..., description="同步目标数据ID")
    task_source_list_id: str = Field(..., description="同步来源数据ID")
    column_name: str = Field(..., description="列名")
    target_data: Any = Field(..., description="目标数据")
    source_data: Any = Field(..., description="源数据")
    is_same: bool = Field(..., description="是否相同")

# 存储在数据库中的目源对比结果模型
class TaskTsContrastResultInDB(TaskTsContrastResultBase):
    id: PyObjectId = Field(default_factory=PyObjectId, alias="_id")

    class Config:
        allow_population_by_field_name = True
        arbitrary_types_allowed = True
        json_encoders = {
            ObjectId: str
        }

# 执行结果响应模型
class ExecutionResultResponse(BaseModel):
    execution_log: TaskDataSyncExecutionLogInDB
    target_data_count: int
    source_data_count: int
    contrast_result_count: int
    different_count: int

    class Config:
        arbitrary_types_allowed = True
        json_encoders = {
            datetime: lambda dt: dt.isoformat() if dt else None
        }